package pl.umk.mat.fred.unicore.urc.storagemanagement.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.TreeViewer;

import pl.umk.mat.fred.unicore.urc.storagemanagement.StorageManagementActivator;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.RootNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.StorageNode;

public class HideShowStoragesAction extends Action {

	private TreeViewer viewer;
	
	public HideShowStoragesAction(TreeViewer viewer) {
		super();
		this.viewer = viewer;
		this.setText("Hide Storages");
		this.setToolTipText("Hide Storages");
		this.setImageDescriptor(getHideImage());
	}
	
	public void run() {
		RootNode rootNode = (RootNode) viewer.getInput();
		boolean visible = rootNode.areStoragesVisible();
		visible = !visible;
		if (visible) {
			viewer.expandToLevel(1);
			this.setText("Hide Storages");
			this.setToolTipText("Hide Storages");
			this.setImageDescriptor(getHideImage());
		} else {
			this.setText("Show Storages");
			this.setToolTipText("Show Storages");
			this.setImageDescriptor(getShowImage());
		}
		rootNode.setStoragesVisible(visible);
		viewer.refresh(true);
	}
	
	private ImageDescriptor getHideImage() {
		ImageDescriptor image = (ImageDescriptor)StorageManagementActivator.getDefault().getObjectFromCache(StorageNode.ICON_RED_NAME);
		if (image == null) {
		  image = ImageDescriptor.createFromURL(StorageManagementActivator.getDefault().getBundle().getEntry("/icons/database_red.png"));
		  StorageManagementActivator.getDefault().setObjectToCache(StorageNode.ICON_RED_NAME, image);  
		}
		return image;
	}
	
	private ImageDescriptor getShowImage() {
		ImageDescriptor image = (ImageDescriptor)StorageManagementActivator.getDefault().getObjectFromCache(StorageNode.ICON_GREEN_NAME);
		if (image == null) {		    
		  image = ImageDescriptor.createFromURL(StorageManagementActivator.getDefault().getBundle().getEntry("/icons/database_green.png"));
		  StorageManagementActivator.getDefault().setObjectToCache(StorageNode.ICON_GREEN_NAME, image);
		}
		return image;
	}
}
